package com.fang.algorithm.zuo.sort;

import java.util.Arrays;

/**
 * @author lingxiao.fang
 * @Desc 堆排序
 * @createTime 2025/2/12 11:14
 */
public class Test08_HeapSort {

    public static void main(String[] args) {
        int[] arr = {3, 2, 1, 0, 10, 8, 9};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    private static void heapSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        // 构建大根堆
        // 方案一：通过一个个数值push操作,自下而上找其父节点 复杂度O(logN)
//        for (int i = 1; i < arr.length; i++) {
//            heapInsert(arr, i);
//        }
        // 方案二：通过自上而下的调整 复杂度O(N)
        for (int i = arr.length - 1; i >= 0; i--) {
            heapify(arr, i, arr.length);
        }
        // 将大根堆的头节点和最后一个节点进行交换
        int heapSize = arr.length;
        heapSize--;
        swap(arr, 0, heapSize);
        while (heapSize > 0) {
            heapSize--;
            heapify(arr, 0, heapSize);
            swap(arr, 0, heapSize);
        }
    }

    private static void heapify(int[] arr, int parentIndex, int heapSize) {
        // 按照从0开始的大根堆的查找规则，其左子节点位置 = 2 * i + 1;右节点位置 = 2 * i + 2;
        int childLeftIndex = 2 * parentIndex + 1;
        while (childLeftIndex < heapSize) {
            // 向下比较，如果右节点的值存在 && 右节点值大于左节点，则拿右节点的值和父节点交换，否则
            int childRightIndex = childLeftIndex + 1;
            int largestIndex = childRightIndex < heapSize && arr[childRightIndex] > arr[childLeftIndex] ? childRightIndex : childLeftIndex;
            largestIndex = arr[parentIndex] > arr[largestIndex] ? parentIndex : largestIndex;
            if (largestIndex == parentIndex) {
                break;
            }
            swap(arr, parentIndex, largestIndex);
            parentIndex = largestIndex;
            childLeftIndex = 2 * parentIndex + 1;
        }
    }

    private static void heapInsert(int[] arr, int childIndex) {
        int parentIndex = (childIndex - 1) / 2;
        while (arr[childIndex] > arr[parentIndex]) {
            swap(arr, childIndex, parentIndex);
            childIndex = parentIndex;
            parentIndex = (childIndex - 1) / 2;
        }
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
